<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医生ID" prop="doctorId">
        <el-input
          v-model="queryParams.doctorId"
          placeholder="请输入医生ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="排班日期" prop="date">
        <el-date-picker clearable
          v-model="queryParams.date"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择排班日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-input
          v-model="queryParams.startTime"
          placeholder="请输入开始时间"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-input
          v-model="queryParams.endTime"
          placeholder="请输入结束时间"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:schedule:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:schedule:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:schedule:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:schedule:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scheduleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="排班记录ID" align="center" prop="id" />
      <el-table-column label="医生ID" align="center" prop="doctorId" />
      <el-table-column label="医生姓名" align="center" prop="name" />
      <el-table-column label="排班日期" align="center" prop="date" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" />
      <el-table-column label="结束时间" align="center" prop="endTime" />
      <el-table-column label="可用挂号数量" align="center" prop="availableSlots" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:schedule:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:schedule:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改医生排班管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="scheduleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择医生" prop="doctorId">
          <el-input 
            v-model="form.name" 
            placeholder="请选择医生" 
            readonly
            style="width: 70%; margin-right: 10px"
            @click.native="openDoctorSelectDialog"
          />
          <el-button 
            type="primary" 
            @click="openDoctorSelectDialog"
          >
            选择医生
          </el-button>
        </el-form-item>
        <el-form-item label="排班日期" prop="date">
          <el-date-picker clearable
            v-model="form.date"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择排班日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-time-picker
            v-model="form.startTime"
            placeholder="请选择开始时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
          ></el-time-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-picker
            v-model="form.endTime"
            placeholder="请选择结束时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
          ></el-time-picker>
        </el-form-item>
        <el-form-item label="可用挂号数量" prop="availableSlots">
          <el-input v-model="form.availableSlots" placeholder="请输入可用挂号数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择医生对话框 -->
    <el-dialog
      v-model="doctorSelectDialogVisible"
      title="选择医生"
      width="500px"
      append-to-body
    >
      <el-table 
        :data="doctorList" 
        @row-click="selectDoctor"
        style="width: 100%;"
        stripe
      >
        <!-- 移除 type="selection" 列，因为现在通过点击行来选择 -->
        <el-table-column label="医生姓名" prop="name" align="center"></el-table-column>
        <el-table-column label="手机号" prop="contactNumber" align="center"></el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="doctorSelectDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Schedule">
import { listSchedule, getSchedule, delSchedule, addSchedule, updateSchedule } from "@/api/manage/schedule";
import { getDoctor, listDoctor } from "@/api/manage/doctor";

const { proxy } = getCurrentInstance();

const scheduleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const doctorSelectDialogVisible = ref(false);
const doctorList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    doctorId: null,
    date: null,
    startTime: null,
    endTime: null,
  },
  rules: {
    doctorId: [
      { required: true, message: "医生ID不能为空", trigger: "blur" }
    ],
    date: [
      { required: true, message: "排班日期不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "结束时间不能为空", trigger: "blur" }
    ],
    availableSlots: [
      { required: true, message: "可用挂号数量不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询医生排班管理列表 */
async function getList() {
  loading.value = true;
  try {
    const response = await listSchedule(queryParams.value);
    scheduleList.value = response.rows;
    total.value = response.total;

    // 提取所有不同的 doctorId
    const doctorIds = [...new Set(scheduleList.value.map(schedule => schedule.doctorId))];

    if (doctorIds.length > 0) {
      // 一次性查询所有医生信息
      const doctorResponse = await listDoctor({ doctorIds }); 
      const doctorMap = {};
      doctorResponse.rows.forEach(doctor => {
        doctorMap[doctor.id] = doctor.name;
      });

      // 为每条排班记录添加医生姓名
      scheduleList.value.forEach(schedule => {
        if (schedule.doctorId in doctorMap) {
          schedule.name = doctorMap[schedule.doctorId];
        }
      });
    }
  } catch (error) {
    console.error('获取排班列表失败:', error);
  } finally {
    loading.value = false;
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    doctorId: null,
    date: null,
    startTime: null,
    endTime: null,
    availableSlots: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("scheduleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加医生排班管理";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  try {
    const response = await getSchedule(_id);
    form.value = response.data;

    // 根据 doctorId 查询就诊人姓名
    if (form.value.doctorId) {
      const query = {
        pageNum: 1,
        pageSize: 1,
        id: form.value.doctorId
      };
      const doctorResponse = await listDoctor(query);
      if (doctorResponse.rows.length > 0) {
        form.value.name = doctorResponse.rows[0].name; // 假设医生姓名的字段名为 name
      }
    }

    open.value = true;
    title.value = "修改医生排班";
  } catch (error) {
    console.error('获取排班信息失败:', error);
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["scheduleRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSchedule(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSchedule(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除医生排班管理编号为"' + _ids + '"的数据项？').then(function() {
    return delSchedule(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/schedule/export', {
    ...queryParams.value
  }, `schedule_${new Date().getTime()}.xlsx`)
}

// 打开选择医生对话框
const openDoctorSelectDialog = async () => {
  try {
    const response = await listDoctor();
    console.log('获取医生列表成功:', response);
    doctorList.value = response.rows;
    console.log('获取医生列表成功:', doctorList.value);
    doctorSelectDialogVisible.value = true;
  } catch (error) {
    console.error('获取医生列表失败:', error);
  }
};

// 处理医生选择
const selectDoctor = (row) => {
  // 记录医生 ID
  form.value.doctorId = row.id; 
  // 记录医生姓名
  form.value.name = row.name; 
  doctorSelectDialogVisible.value = false;
};


getList();
</script>
